// src/api/axiosInstance.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { api } from '@/config/config-params'
import { getToken } from '@/utils/index';
import { loadingService } from "@/utils/loadingServer"
import { useDispatch } from "react-redux"
import { loginOut } from '@/store/slices/loginSlice'
import { clearStorage } from "@/utils/index"
import {useRouter} from "expo-router";


// 创建 Axios 实例
const axiosInstance: AxiosInstance = axios.create<any>({
    baseURL: api, // 替换为你的 API 基础 URL
    timeout: 10000, // 请求超时时间
    headers: {
        'Content-Type': 'application/json',
    } as Record<string, string>, // 类型断言
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    async (config: any) => {
        // 在发送请求之前做些什么

        const token = await getToken() || ""; // 从存储或其他地方获取令牌
        console.log('token', token)
        if (token) {
          config.headers.Authorization = `${token}`;
        }

        return config;
    },
    (error) => {
        // 请求错误时做些什么
        return Promise.reject(error);
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {
        // 对响应数据做些什么


        console.log('response', response.data);
        if (response?.data?.code == 200) {
            loadingService.hide();
            return  Promise.resolve(response.data);
        } else {
            console.log('loginOut', response);
            if (response.data.code == 50) {
                // const router = useRouter();
                clearStorage();
                // router.replace("/")
            };
            return  Promise.reject(response.data);
        }},
    (error) => {
        // 对响应错误做些什么
        if (error.response) {
            console.error('Error Response:', error.response.data);
            loadingService.hide();
        } else if (error.request) {
            console.error('Error Request:', error.request);
            loadingService.hide();
        } else {
            console.error('Error Message:', error.message);
            loadingService.hide();
        }

        loadingService.hide();
        return Promise.reject(error.data);
    }
);

export default axiosInstance;
